package com.controller;

import com.anno.BackLogin;
import com.controller.base.BaseController;
import com.controller.base.Response;
import com.model.BackUser;
import com.service.BackUserService;
import com.utils.from.BackUserFrom;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/backUser")
public class BackUserController extends BaseController {

    @Autowired
    private BackUserService userService;

    @PostMapping("/register")
    public Response register(@Valid BackUserFrom from) {
        ModelMapper mapper = new ModelMapper();
        BackUser user = mapper.map(from, BackUser.class);
        if(userService.checkExists(user)) {
            return fail("用户已存在");
        }
        boolean result = userService.register(user);
        return result ? success("注册成功") : fail("注册失败");
    }

    @PostMapping("/login")
    public Response login(@Valid BackUserFrom from, HttpSession session) {
        // 验证username
        BackUser user = userService.getByUsername(from.getUsername());
        if(user == null) return fail("改用户不存在");
        // 验证password
        boolean passwordFlag = userService.checkPasswordByUser(from.getPassword(), user);
        if(!passwordFlag) return fail("密码错误");
        // 缓存到session
        session.setAttribute("user", user);
        boolean updateFlag = userService.updateLoginTime(user, LocalDateTime.now());
        if (!updateFlag) return fail("登录失败!");
        return success();
    }

    @PostMapping("/getByToken")
    public Response<BackUser> getUser(HttpSession session) {
        BackUser user = (BackUser) session.getAttribute("user");
        if(user == null) return fail();
        user.setPassword("");
        return success(user);
    }

    @PostMapping("/logout")
    public Response logout(HttpSession session) {
        session.removeAttribute("user");;
        return success();
    }

    @BackLogin
    @PostMapping("/list")
    public Response<List<BackUser>> list() {
        List<BackUser> users = userService.findAll();
        users.forEach((user) -> {
            user.setPassword("");
        });
        return success(users);
    }
}
